package com.example.springbootbabyu.service.impl;

import com.example.springbootbabyu.entity.*;
import com.example.springbootbabyu.entity.vo.SkusVo;
import com.example.springbootbabyu.mapper.MemberMapper;
import com.example.springbootbabyu.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 功能
 * 作者：梦天
 * 日期：2025/4/21 21:50
 */
@Service
@Slf4j
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberMapper memberMapper;

    @Override
    public List<CartVo> getCard(String userId) {
        return memberMapper.getCard(userId);
    }

    @Override
    public PreOrderVo getPreOrder(String userId) {
        PreOrderVo preOrderVo = new PreOrderVo();
        List<UserAddressVo> userAddresses = memberMapper.getUserAddress(userId);
        log.info("userAddresses:{}", userAddresses);
        preOrderVo.setUserAddresses(userAddresses);
        List<OrderGoodsVo> orderGoods = memberMapper.getOrderGoods(userId);
        log.info("orderGoods:{}", orderGoods);
        preOrderVo.setGoods(orderGoods);
        OrderSummaryVo orderSummary = memberMapper.getOrderSummary(userId);
        int totalPayPrice = 0;
        for (OrderGoodsVo goods : orderGoods) {
            totalPayPrice += goods.getTotalPayPrice();
        }
        orderSummary.setTotalPayPrice(totalPayPrice);
        log.info("orderSummary:{}", orderSummary);
        preOrderVo.setSummary(orderSummary);
        return preOrderVo;
//        return memberMapper.getPreOrder(userId);
    }

    @Override
    public String mergeCart(String userId, List<CartItemDTO> cartItemDTO) {
        // 合并购物车，遍历cartItemDTO，将其中的商品添加到购物车中
        if (cartItemDTO == null || cartItemDTO.size() == 0) {
            return "success";
        }
        for (CartItemDTO item : cartItemDTO) {
            memberMapper.mergeCart(userId, item.getSkuId(), item.getCount(), item.getSelected());
        }
        return "success";
    }

    @Override
    public CartMergeDTO getMergeCart(String userId) {
        return memberMapper.getMergeCart(userId);
    }

    @Override
    public CartItemDTO addCart(String userId, CartItemDTO cartItemDTO) {
        return memberMapper.addCart(userId, cartItemDTO.getSkuId(), cartItemDTO.getCount());
    }

    @Override
    public String deleteCart(String userId, List<String> id) {
        if (id == null || id.size() == 0) {
            return "success";
        }
        for (String skuId : id) {
            memberMapper.deleteCart(userId, skuId);
        }
        return "success";
    }

    @Override
    public OrderCreateResponse createOrder(String userId, CreateOrder createOrder) {

        // 1. 获取并验证收货地址
        UserAddress address = memberMapper.getAddressById(createOrder.getAddressId(), userId);
        if (address == null) {
            throw new RuntimeException("收货地址不存在或不属于当前用户");
        }

        // 2. 计算商品总金额和总数量
        List<CartItemDTO> goods = createOrder.getGoods();
        int totalNum = 0;
        int totalPayPrice = 0;
        for (CartItemDTO item : goods) {
            // 获取SKU实时价格（分）
            double skuPrice = memberMapper.getSkuCurrentPrice(item.getSkuId());
            if (skuPrice <= 0) {
                throw new RuntimeException("商品SKU不存在: " + item.getSkuId());
            }
            totalNum += item.getCount();
            totalPayPrice += skuPrice * item.getCount();
        }

        // 3. 生成订单ID
        String orderId = UUID.randomUUID().toString().replace("-", "");

        // 4. 创建订单主记录
        Orders order = new Orders();
        order.setId(orderId);
        order.setUserId(userId);
        order.setTotalNum(totalNum);
        order.setTotalMoney(totalPayPrice);
        order.setPostFee(0);
        order.setPayMoney(totalPayPrice);
        order.setStatus(0); // 待支付
        order.setPayType(createOrder.getPayType());
        order.setPayChannel(createOrder.getPayChannel());
        order.setDeliveryTimeType(createOrder.getDeliveryTimeType());
        order.setBuyerMessage(createOrder.getBuyerMessage());
        order.setReceiverName(address.getReceiver());
        order.setReceiverPhone(address.getContact());
//        order.setReceiverProvince(address.getProvinceCode());
//        order.setReceiverCity(address.getCityCode());
//        order.setReceiverCounty(address.getCountyCode());
        order.setReceiverAddress(address.getAddress());
//        order.setPayLatestTime(new Date(System.currentTimeMillis() + 15 * 60 * 1000)); // 15分钟支付时限
        order.setAddressId(createOrder.getAddressId());

        memberMapper.createOrder(order);
//
//        // 5. 创建订单商品项
//        createOrderItems(userId, orderId, createOrder.getGoods());
        for (CartItemDTO item : goods) {
            String itemId = UUID.randomUUID().toString().replace("-", "");

            // 获取SKU详情
            SkuDetail sku = memberMapper.getSkuDetail(item.getSkuId());
            log.info("sku:{}", sku);
            if (sku == null) {
                throw new RuntimeException("无效的SKU: " + item.getSkuId());
            }

            memberMapper.createOrderItem(
                    itemId,
                    userId,
                    orderId,
                    item.getSkuId(),
                    item.getCount(),
                    sku.getPrice(), // 以分为单位的价格
                    sku.getAttrsText()
            );
        }
//
//        // 6. 构建响应
//        return buildResponse(orderId, summary.getTotalPayPrice());
        OrderCreateResponse response = new OrderCreateResponse();
        response.setId(orderId);

        // 设置时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        response.setCreateTime(sdf.format(new Date()));
        response.setOrderStatus(0);
        response.setPayChannel(1);
        response.setPayLatestTime(sdf.format(new Date(System.currentTimeMillis() + 15 * 60 * 1000)));
        response.setPayMoney(totalPayPrice);
        // 清空购物车
        memberMapper.deleteCartByUserId(userId);
        return response;
    }

//    @Override
//    public OrderCreateResponse createOrder(String userId, CreateOrder createOrder) {
//        // 生成ID
//        String orderId = UUID.randomUUID().toString();
//        log.info("createOrder, orderId:{}", orderId);
//        memberMapper.createOrder(userId, orderId, createOrder.getDeliveryTimeType(), createOrder.getPayType(), createOrder.getPayChannel(), createOrder.getBuyerMessage(), createOrder.getAddressId());
//        for (CartItemDTO orderItem : createOrder.getGoods()) {
//            String id = UUID.randomUUID().toString();
//            memberMapper.createOrderItem(id,userId, orderId, orderItem.getSkuId(), orderItem.getCount());
//        }
//        OrderCreateResponse response = new OrderCreateResponse();
//        response.setId(orderId);
//        // 定义当前时间，格式 yyyy-MM-dd HH:mm:ss
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String currentTime = sdf.format(new Date());
//        response.setCreateTime(currentTime);
//        response.setOrderStatus(0);
//        response.setPayChannel(1);
//        // 最后支付时间, 支付超时时间为15分钟
//        String payLatestTime = sdf.format(new Date(System.currentTimeMillis() + 15 * 60 * 1000));
//        response.setPayLatestTime(payLatestTime);
//        List<OrderGoodsVo> orderGoods = memberMapper.getOrderGoods(userId);
//        OrderSummaryVo orderSummary = memberMapper.getOrderSummary(userId);
//        int totalPayPrice = 0;
//        for (OrderGoodsVo goods : orderGoods) {
//            totalPayPrice += goods.getTotalPayPrice();
//        }
//        response.setPayMoney(totalPayPrice);
//        return response;
//    }

    @Override
    public OrderDetailResponse getOrderDetail(String userId, String id) {
        OrderDetailResponse response = memberMapper.getOrderDetail(userId, id);
        List<SkusVo> skus = memberMapper.getCartByUserId(userId);
        response.setSkus(skus);
        // 业务逻辑补充
        if (response != null) {
            // 计算预计到达时间
            if (response.getConsignTime() != null) {
                LocalDateTime consignTime = LocalDateTime.parse(
                        response.getConsignTime(),
                        DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
                );
                response.setArrivalExpectedTime(
                        consignTime.plusDays(3).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
                );
            }
        }

        return response;
    }

    @Override
    public OrderList queryUserOrders(String userId, Integer orderState, Integer page, Integer pageSize) {
        // 1. 查询总记录数
        int count = memberMapper.countOrdersByUserIdAndState(userId, orderState);

        // 2. 分页查询订单主信息
        int offset = (page - 1) * pageSize;
        List<Order> orders = memberMapper.selectOrdersByUserIdAndState(userId, orderState, offset, pageSize);

        List<String> orderIds = orders.stream().map(Order::getId).collect(Collectors.toList());

        // 3. 查询订单商品项
        List<OrderItem> orderItems = new ArrayList<>();
        if (!orderIds.isEmpty()) {
            orderItems = memberMapper.selectOrderItemsByOrderIds(orderIds);
        }

        // 4. 将订单项分组到每个订单
        Map<String, List<OrderSkus>> orderSkusMap = orderItems.stream()
                .collect(Collectors.groupingBy(OrderItem::getOrderId,
                        Collectors.mapping(this::convertToOrderSkus, Collectors.toList())));

        // 5. 组装OrderListItemDTO列表
        List<OrderListItemDTO> items = orders.stream().map(order -> {
            OrderListItemDTO dto = new OrderListItemDTO();
            dto.setId(order.getId());
            dto.setCreateTime(formatTime(order.getCreateTime()));
            dto.setOrderStatus(convertStatus(order.getStatus()));
            dto.setPayType(String.valueOf(order.getPayType()));
            dto.setPayMoney(order.getTotalMoney() / 100.0);
            dto.setPostFee(order.getPostFee() / 100.0);
            dto.setSkus(orderSkusMap.getOrDefault(order.getId(), Collections.emptyList()));

            // 设置倒计时
            if (order.getStatus() == 0 && order.getPayLatestTime() != null) {
                dto.setCountdown(calculateCountdown(order.getPayLatestTime()));
            }
            return dto;
        }).collect(Collectors.toList());

        // 6. 构建返回结果
        OrderList result = new OrderList();
        result.setCounts(count);
        result.setPage(page);
        result.setPageSize(pageSize);
        result.setPages(String.valueOf((count + pageSize - 1) / pageSize));
        result.setItems(items);

        return result;
    }

    // 状态转换
    private Integer convertStatus(Short status) {
        if (status == null) return null;
        switch (status) {
            case 0:
                return 1; // 待付款
            case 2:
                return 3; // 已发货
            case 3:
                return 5; // 已完成
            default:
                return Integer.valueOf(status); // 其他状态如取消等
        }
    }

    // 时间格式化
    private String formatTime(LocalDateTime time) {
        if (time == null) return null;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return time.format(formatter);
    }

    // 计算倒计时
    private String calculateCountdown(LocalDateTime payLatestTime) {
        LocalDateTime now = LocalDateTime.now();
        if (now.isAfter(payLatestTime)) return "00:00:00";

        Duration duration = Duration.between(now, payLatestTime);
        long seconds = duration.getSeconds();
        long hours = seconds / 3600;
        long minutes = (seconds % 3600) / 60;
        long secs = seconds % 60;

        return String.format("%02d:%02d:%02d", hours, minutes, secs);
    }

    // 转换订单项为OrderSkus
    private OrderSkus convertToOrderSkus(OrderItem item) {
        OrderSkus skus = new OrderSkus();
        skus.setId(item.getGoodsId()); // 商品ID对应goods.id
        skus.setImage(item.getPicture());
        skus.setName(item.getGoodsName());
        skus.setAttrText(item.getAttrsText());
        skus.setRealPay(item.getPrice() / 100.0); // 分转元
        skus.setQuantity(item.getQuantity());
        return skus;
    }
}